import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { MavenUtils } from './mavenUtils';

/**
 * POM文件装饰器，提供额外的UI功能
 */
export class PomFileDecorator {
    private mavenUtils: MavenUtils;
    private decorationType: vscode.TextEditorDecorationType;
    private statusBarItem: vscode.StatusBarItem;
    
    constructor(context: vscode.ExtensionContext) {
        this.mavenUtils = new MavenUtils();
        
        // 创建依赖冲突的装饰类型
        this.decorationType = vscode.window.createTextEditorDecorationType({
            backgroundColor: 'rgba(240, 40, 40, 0.2)',
            overviewRulerColor: 'rgba(240, 40, 40, 0.7)',
            overviewRulerLane: vscode.OverviewRulerLane.Right
        });
        
        // 创建悬浮按钮
        this.statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
        this.statusBarItem.text = "$(list-unordered) 分析依赖";
        this.statusBarItem.tooltip = "Maven Helper: 分析依赖";
        this.statusBarItem.command = "maven-helper.analyzeDependencies";
        
        // 注册事件监听
        context.subscriptions.push(
            vscode.window.onDidChangeActiveTextEditor(this.handleEditorChange, this),
            vscode.workspace.onDidOpenTextDocument(this.checkForConflicts, this),
            vscode.workspace.onDidChangeTextDocument(event => this.checkForConflicts(event.document), this),
            this.decorationType,
            this.statusBarItem
        );
        
        // 初始化当前编辑器
        this.handleEditorChange(vscode.window.activeTextEditor);
    }
    
    /**
     * 处理编辑器变化事件
     */
    private handleEditorChange(editor: vscode.TextEditor | undefined): void {
        if (editor && editor.document.fileName.endsWith('pom.xml')) {
            this.statusBarItem.show();
            this.checkForConflicts(editor.document);
        } else {
            this.statusBarItem.hide();
        }
    }
    
    /**
     * 检查POM文件中的依赖冲突
     */
    private async checkForConflicts(document: vscode.TextDocument): Promise<void> {
        if (!document.fileName.endsWith('pom.xml')) {
            return;
        }
        
        // 使用正则表达式查找依赖声明
        const text = document.getText();
        const dependencyPattern = /<dependency>[\s\S]*?<\/dependency>/g;
        const decorations: vscode.DecorationOptions[] = [];
        
        // 保存我们已经看到的依赖
        const seen = new Map<string, { version: string, range: vscode.Range }>();
        
        let match: RegExpExecArray | null;
        while ((match = dependencyPattern.exec(text)) !== null) {
            const depText = match[0];
            const groupIdMatch = depText.match(/<groupId>(.*?)<\/groupId>/);
            const artifactIdMatch = depText.match(/<artifactId>(.*?)<\/artifactId>/);
            const versionMatch = depText.match(/<version>(.*?)<\/version>/);
            
            if (groupIdMatch && artifactIdMatch) {
                const groupId = groupIdMatch[1];
                const artifactId = artifactIdMatch[1];
                const version = versionMatch ? versionMatch[1] : '';
                
                const key = `${groupId}:${artifactId}`;
                
                // 获取依赖的范围
                const startPos = document.positionAt(match.index);
                const endPos = document.positionAt(match.index + match[0].length);
                const range = new vscode.Range(startPos, endPos);
                
                // 检查是否有冲突
                if (seen.has(key) && seen.get(key)!.version !== version) {
                    // 标记当前依赖为冲突
                    decorations.push({
                        range,
                        hoverMessage: `依赖冲突: ${key} 版本 ${version} 与 ${seen.get(key)!.version} 冲突`
                    });
                    
                    // 也标记之前的依赖为冲突
                    decorations.push({
                        range: seen.get(key)!.range,
                        hoverMessage: `依赖冲突: ${key} 版本 ${seen.get(key)!.version} 与 ${version} 冲突`
                    });
                }
                
                seen.set(key, { version, range });
            }
        }
        
        // 应用装饰
        for (const editor of vscode.window.visibleTextEditors) {
            if (editor.document === document) {
                editor.setDecorations(this.decorationType, decorations);
            }
        }
    }
}
